package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.business.SpecialSaleType;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.CustomDigitalClock;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 *  限时特卖
 * @author fbl
 */
public class TimeLimitedSaleActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.time_limit_head_text) TextView mHeadText;
	@ViewInject(id = R.id.time_radio0,click = "butClick") RadioButton radio0;
	@ViewInject(id = R.id.time_radio1,click = "butClick") RadioButton radio1;
	@ViewInject(id = R.id.time_radio2,click = "butClick") RadioButton radio2;
	@ViewInject(id = R.id.time_limit_loading_text) TextView mLoadingText;
	@ViewInject(id = R.id.special_empty_relat) RelativeLayout mEmptyRelat;
	private TimeLimitedSaleAdapter mTimeLimitedSaleAdapter;
	private String orderProperty = "endTime";
	private String orderSequence = "asc";

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private int nowPage = 1;
	private List<Product> mSales;
	private long nowDate;
	private Handler mHandler = new MyHandler(this);

	private SpecialSaleType mSpecialSaleType = SpecialSaleType.active;


	//-----------------------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_time_limit);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.main_time_limit_sale);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.time_limited_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mTimeLimitedSaleAdapter = new TimeLimitedSaleAdapter(this,R.layout.item_time_limited);
		mRefreshListView.setAdapter(mTimeLimitedSaleAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);

		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent,View ciew, int position, long id) {
				Intent intent = new Intent(TimeLimitedSaleActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", mTimeLimitedSaleAdapter.getData().get(position-1).getId()+"");
				intent.putExtra("saleType", mSpecialSaleType);
				startActivity(intent);
			}
		});

		mLoadMoreProxy.refreshing();

	}


	//UI Handler-----------------------------------------

	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if (mActivity.get() != null ) {
				switch (msg.what) {
				case 0:
					mRefreshListView.onRefreshComplete();
					mTimeLimitedSaleAdapter.update(mSales);
					canclick(true);
					break;
				case 1:
					mRefreshListView.onRefreshComplete();
					mTimeLimitedSaleAdapter.append(mSales);
					canclick(true);
					break;
				default:
					break;
				}
			}
		}

	}


	//OnLoadDataActionListener ------------------------------

	@Override
	public void onRefresh(int page) {
		updateTimeLimitListAsync(1,true);
	}

	@Override
	public void onLoadMore(int page) {
		nowPage ++;
		updateTimeLimitListAsync(nowPage, false);
	}



	//UI Event --------------------------------------

	public void butClick(View v){
		if( v == radio0 ){
			mSpecialSaleType = SpecialSaleType.active;
			orderProperty = "endTime";
			orderSequence = "asc";
			mHeadText.setText("抢购中...");
			canclick(false);
			onRefresh(1);
		}
		if( v == radio1 ){
			mSpecialSaleType = SpecialSaleType.next;
			orderProperty = "startTime";
			orderSequence = "asc";
			mHeadText.setText("即将开始...");
			canclick(false);
			onRefresh(1);
		}
		if( v == radio2 ){
			mSpecialSaleType = SpecialSaleType.history;
			orderProperty = "endTime";
			orderSequence = "desc";
			mHeadText.setText("已结束...");
			canclick(false);
			onRefresh(1);
		}
	}

	//------------------------------------------------

	private void updateTimeLimitListAsync(final int pageNum,final boolean isRefresh){
		//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(TimeLimitedSaleActivity.this);
					PageEntity<Product> entry = client.active(mSpecialSaleType.toString(), pageNum, 20, orderProperty, orderSequence);
					nowDate = entry.getNowDate(); //get date...
					int totlePage = entry.getTotalPages(); // get total pages...
					mSales = entry.getContent(); //get sale items ...
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mSales = null;
					}
				} catch (WebException e) {

					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mSales = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);
	}

	private void canclick (boolean b){
		radio0.setClickable(b);
		radio1.setClickable(b);
		radio2.setClickable(b);
		setView(!b);

	}
	private void setView(boolean visible){
		if(visible){
			mLoadingText.setVisibility(View.VISIBLE);
		}else {
			mLoadingText.setVisibility(View.GONE);
		}

	}

	//-----------------------------------------------

	public class TimeLimitedSaleAdapter extends AbsViewHolderAdapter<Product>{

		public TimeLimitedSaleAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {

			ImageView mImageView = getViewFromHolder(R.id.item_time_limit_right_image);
			TextView mNameTextView = getViewFromHolder(R.id.item_time_limit_name_txt);
			TextView mPriceTextView = getViewFromHolder(R.id.item_time_limit_price_txt);
			TextView mMarketPriceTextView = getViewFromHolder(R.id.item_time_limit_market_price_txt);
			TextView mDiscountTextView = getViewFromHolder(R.id.item_time_limit_discount_text);
			TextView mNextSpecialTextView = getViewFromHolder(R.id.item_limit_text);

			mMarketPriceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

			ImageLoader.getInstance().displayImage(itemData.getImage(),mImageView);
			mNameTextView.setText(itemData.getName());
			mPriceTextView.setText("￥"+itemData.getPrice());
			if( itemData.getDiscount() == null){
				mDiscountTextView.setVisibility(View.GONE);	
			}else {
				mDiscountTextView.setText((itemData.getDiscount().multiply(BigDecimal.valueOf(10)))+"折");
			}

			//			mDiscountTextView.setText((itemData.getDiscount() == 0 ? 1:itemData.getDiscount())+"折");
			mMarketPriceTextView.setText("￥"+itemData.getReferencePrice());

			long endTime = itemData.getEndTime();
			long begindate = itemData.getStartTime();
			CustomDigitalClock remainTime = (CustomDigitalClock) getViewFromHolder(R.id.item_remain_time_text);
			if( mSpecialSaleType.equals(SpecialSaleType.active)){
				remainTime.setVisibility(View.VISIBLE);
				mNextSpecialTextView.setText(R.string.special_end_time);
				remainTime.setEndTime(System.currentTimeMillis()+(endTime-nowDate)); //System.currentTimeMillis()+   /date
				App.showLog(System.currentTimeMillis()+(endTime-nowDate));
			}else if (mSpecialSaleType.equals(SpecialSaleType.next)) {
				remainTime.setVisibility(View.VISIBLE);
				mNextSpecialTextView.setText(R.string.special_begin_time);
				remainTime.setEndTime(System.currentTimeMillis()+(begindate-nowDate));
			}else if(mSpecialSaleType.equals(SpecialSaleType.history)){
				mNextSpecialTextView.setText(R.string.special_history_time);
				remainTime.setVisibility(View.GONE);
			}
			//remainTime.setEndTime(System.currentTimeMillis()+(enddate-nowDate)); //System.currentTimeMillis()+   /date
			remainTime.setClockListener(new CustomDigitalClock.ClockListener() {

				@Override
				public void timeEnd() {
					mLoadMoreProxy.refreshing();
				}
				@Override
				public void remainFiveMinutes() {
				}
			} );
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
